package com.itita.ww2.handler.requesthandler.mission;

import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.game.user.UserInventoryManager;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.model.user.battle.BaseBattleState.BattleType;
import com.itita.ww2.model.user.battle.MissionBattleState;
import com.itita.ww2.utils.handler.IRequestOper;

/**
 * 通关副本
 * @author NorthLan
 *
 */
public class MissionEnd implements IRequestOper {
	private static final Logger logger = LoggerFactory.getLogger(MissionEnd.class);

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		UserProfile userProfile = UserService.getInstance().getUserProfile(user);
		boolean victory = params.getBool("victory");
		ISFSObject army = params.getSFSObject("army"); // 兵
		// 
		MissionBattleState userState = userProfile.getBattleManager().getBattleState(BattleType.Mission);
		if (userState == null) {
			logger.error("User hasn't start mission.");
			throw new WW2Exception();
		}
		String missionId = userState.getMissionId();
		
		userState.setLastBattleArmy(army);
		boolean isFirst = userProfile.getMissionManager().isFirst(missionId);
		userState.setState(isFirst);

		ISFSObject rewardObj = SFSObject.newInstance();
		if (victory) {
			userProfile.getWMManager().getUserUnlockDataMgr().unlockCity(userState.getBlockId(), userState.getCityId());

			UserInventoryManager inventory = userProfile.getInventory();
			inventory.backup();
			try {
				rewardObj = userProfile.getMissionManager().missionComplete(missionId, army.getKeys());
			} catch (Exception e) {
				inventory.rollback();
				// 结束战斗
				userProfile.getBattleManager().endBattle(true, victory);
				throw e;
			} finally {
				inventory.clean();
			}
			inventory.update();
			inventory.sync();
		}
		// 结束战斗
		userProfile.getBattleManager().endBattle(true, victory);
		// 消耗体力
		if (!userProfile.getUserInfo().fatigueCostByMission(missionId)) {
			throw new WW2Exception(WW2ExceptionCode.USER_FATIGUE_NOT_ENOUGH);
		}
		
		// 回传
		ISFSObject backObj = new SFSObject();
		if (victory) {
			// 奖励
			backObj.putSFSObject("reward", rewardObj);
			backObj.putBool("isFirst", isFirst);
		}
		//		logger.debug("data:\n{}", backObj.toJson());
		MessageHandler.getInstance().sendMsg(requestCMD, backObj, user, null, true);
		return true;
	}

}
